<template>
  <div v-if="visible" class="modal-overlay preview-overlay" @click="closeModal">
    <div class="preview-modal" @click.stop>
      <div class="preview-header">
        <h3 class="preview-title">模型预览</h3>
        <button class="close-btn" @click="closeModal">&times;</button>
      </div>
      
      <div class="preview-body">
        <!-- 文件信息 -->
        <div class="file-info-preview">
          <p class="file-size">{{ fileSize }} MB</p>
          
          <div v-if="zipParsingStatus" class="zip-status">
            <p :class="{ 'status-success': zipParsingStatus.includes('成功'), 'status-error': zipParsingStatus.includes('失败') }">
              {{ zipParsingStatus }}
            </p>
          </div>

          <!-- 多模型选择器 -->
          <div v-if="extractedModels.length > 1" class="model-selector">
            <p class="selector-label">选择模型 ({{ extractedModels.length }} 个文件):</p>
            <div class="model-list">
              <button 
                v-for="(model, index) in extractedModels" 
                :key="index"
                @click="switchModel(index)"
                :class="['model-item', { 'active': currentModelIndex === index }]"
              >
                <span class="model-name">{{ model.name.split('/').pop() }}</span>
                <span v-if="currentModelIndex === index" class="active-indicator">✓</span>
              </button>
            </div>
          </div>
        </div>

        <div class="large-model-viewer-container">
          <!-- 3D模型查看器 -->
          <model-viewer
            v-if="modelUrl && !zipParsingStatus.includes('正在解析') && !zipParsingStatus.includes('失败')"
            :src="modelUrl"
            alt="3D Model"
            class="large-model-viewer"
            auto-rotate
            camera-controls
            environment-image="legacy"
            poster=""
            shadow-intensity="1"
            field-of-view="30deg"
            min-field-of-view="10deg"
            max-field-of-view="60deg"
            camera-orbit="0deg 75deg auto"
            min-camera-orbit="auto auto 0.05m"
            max-camera-orbit="auto auto auto"
            interaction-prompt="auto"
          >
            <!-- 加载状态 -->
            <div slot="poster" class="loading-overlay">
              <div class="loading-content">
                <div class="loading-spinner"></div>
                <p class="loading-text">加载3D模型中...</p>
              </div>
            </div>
          </model-viewer>
          
          <div v-else-if="zipParsingStatus.includes('正在解析')" class="large-model-viewer">
            <div class="model-placeholder">
              <p>正在解析ZIP文件...</p>
              <p class="model-filename">{{ fileName }}</p>
            </div>
          </div>
          
          <div v-else-if="zipParsingStatus.includes('失败')" class="large-model-viewer">
            <div class="model-placeholder">
              <p>解析失败</p>
              <p class="error-message">{{ zipParsingStatus }}</p>
            </div>
          </div>
          
          <div v-else class="large-model-viewer">
            <div class="model-placeholder">
              <p>等待解析...</p>
              <p class="model-filename">{{ fileName }}</p>
            </div>
          </div>
        </div>
      </div>

      <div class="preview-footer">
        <button class="btn-cancel" @click="closeModal">关闭</button>
        <button 
          class="btn-confirm" 
          @click="handleConfirm"
          :disabled="isLoading"
        >
          <span v-if="isLoading">处理中...</span>
          <span v-else>确认</span>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  file: {
    type: File,
    default: null
  },
  isLoading: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['close', 'confirm'])

// 响应式数据
const modelUrl = ref('')
const zipParsingStatus = ref('')
const extractedModels = ref([])
const currentModelIndex = ref(0)

// 计算属性
const fileSize = ref(0)
const fileName = ref('')

// 方法
const closeModal = () => {
  emit('close')
}

const handleConfirm = () => {
  emit('confirm')
}

// 解析ZIP文件
const parseZipFile = async (file) => {
  if (!window.JSZip) {
    throw new Error('JSZip 库未加载')
  }
  
  zipParsingStatus.value = '正在解析ZIP文件...'
  
  try {
    const zip = new window.JSZip()
    const zipContent = await zip.loadAsync(file)
    const models = []
    
    // 查找ZIP中的3D模型文件
    const modelExtensions = ['.glb', '.gltf']
    const promises = []
    
    zipContent.forEach((relativePath, zipEntry) => {
      const fileName = relativePath.toLowerCase()
      const hasValidExtension = modelExtensions.some(ext => fileName.endsWith(ext))
      
      if (hasValidExtension && !zipEntry.dir) {
        const promise = zipEntry.async('blob').then((blob) => {
          const url = URL.createObjectURL(blob)
          models.push({
            name: relativePath,
            url: url
          })
        })
        promises.push(promise)
      }
    })
    
    await Promise.all(promises)
    
    if (models.length === 0) {
      throw new Error('ZIP文件中未找到GLB或GLTF格式的3D模型文件')
    }
    
    extractedModels.value = models
    currentModelIndex.value = 0
    modelUrl.value = models[0]?.url || ''
    zipParsingStatus.value = `成功解析，找到 ${models.length} 个3D模型文件`
    
  } catch (error) {
    console.error('ZIP解析错误:', error)
    zipParsingStatus.value = `解析失败: ${error instanceof Error ? error.message : '未知错误'}`
    throw error
  }
}

// 切换ZIP中的模型
const switchModel = (index) => {
  if (index >= 0 && index < extractedModels.value.length) {
    const selectedModel = extractedModels.value[index]
    if (selectedModel) {
      currentModelIndex.value = index
      modelUrl.value = selectedModel.url
    }
  }
}

// 清理预览资源
const cleanupPreviewResources = () => {
  // 清理已创建的URL对象
  if (modelUrl.value && modelUrl.value.startsWith('blob:')) {
    URL.revokeObjectURL(modelUrl.value)
  }
  
  // 清理提取的模型URL
  extractedModels.value.forEach(model => {
    if (model.url.startsWith('blob:')) {
      URL.revokeObjectURL(model.url)
    }
  })
  
  // 重置状态
  modelUrl.value = ''
  zipParsingStatus.value = ''
  extractedModels.value = []
  currentModelIndex.value = 0
}

// 监听文件变化
watch(() => props.file, async (newFile) => {
  if (!newFile) return
  
  // 清理之前的资源
  cleanupPreviewResources()
  
  // 更新文件信息
  fileSize.value = (newFile.size / 1024 / 1024)
  fileName.value = newFile.name
  
  const fileExtension = newFile.name.toLowerCase().substring(newFile.name.lastIndexOf('.'))
  
  // 创建文件URL用于model-viewer预览
  if (fileExtension === '.glb' || fileExtension === '.gltf') {
    const url = URL.createObjectURL(newFile)
    modelUrl.value = url
  } else if (fileExtension === '.zip') {
    try {
      await parseZipFile(newFile)
    } catch (error) {
      console.error('ZIP文件解析失败:', error)
    }
  }
}, { immediate: true })

// 组件卸载时清理资源
onUnmounted(() => {
  cleanupPreviewResources()
})
</script>

<style scoped>
/* 模态框样式 */
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.preview-modal {
  background: white;
  border-radius: 15px;
  width: 90%;
  max-width: 1200px;
  max-height: 90vh;
  overflow-y: auto;
  color: #333;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 25px;
  border-bottom: 1px solid #eee;
}

.preview-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 28px;
  cursor: pointer;
  color: #999;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s;
  padding: 0;
  line-height: 1;
}

.close-btn:hover {
  background: #f5f5f5;
  color: #333;
  transform: scale(1.1);
}

.preview-body {
  padding: 25px;
}

.file-info-preview {
  text-align: center;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.file-size {
  font-size: 14px;
  color: #666;
  margin: 0 0 10px 0;
}

.zip-status {
  margin: 10px 0;
}

.status-success {
  color: #28a745;
  font-weight: 500;
}

.status-error {
  color: #dc3545;
  font-weight: 500;
}

.model-selector {
  margin: 20px 0;
}

.selector-label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 10px;
}

.model-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-height: 150px;
  overflow-y: auto;
}

.model-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  background: white;
  cursor: pointer;
  transition: all 0.3s;
}

.model-item:hover {
  border-color: #3742fa;
  background: #f8f9ff;
}

.model-item.active {
  border-color: #3742fa;
  background: #3742fa;
  color: white;
}

.model-name {
  flex: 1;
  text-align: left;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.active-indicator {
  color: inherit;
  font-weight: bold;
}

.large-model-viewer-container {
  height: 500px;
  border-radius: 12px;
  overflow: hidden;
  background: #f0f0f0;
  position: relative;
}

.large-model-viewer {
  width: 100%;
  height: 100%;
  border-radius: 12px;
  background: #e5e9ec;
  display: flex;
  align-items: center;
  justify-content: center;
}

.model-placeholder {
  text-align: center;
  color: #666;
}

.model-placeholder p {
  margin: 5px 0;
  font-size: 16px;
}

.model-filename {
  font-size: 12px;
  color: #999;
  margin: 5px 0 0 0;
  word-break: break-all;
}

.error-message {
  color: #e74c3c !important;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-content {
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3742fa;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 15px;
}

.loading-text {
  color: #666;
  font-size: 14px;
  margin: 0;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.preview-footer {
  display: flex;
  gap: 15px;
  justify-content: flex-end;
  padding: 20px 25px;
  border-top: 1px solid #eee;
  background: #f8f9fa;
}

.btn-cancel {
  background: #6c757d;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
}

.btn-cancel:hover:not(:disabled) {
  background: #5a6268;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(108, 117, 125, 0.3);
}

.btn-confirm {
  padding: 10px 20px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid;
  background: #3742fa;
  color: white;
}

.btn-confirm:disabled {
  background: #ccc;
  cursor: not-allowed;
}
</style>
